namespace ClassyBlog
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using NSubstitute;

    public static class MvcTestHelper
    {
        private const string AppPathModifier = "/$(SESSION)";

        public static HttpContextBase CreateHttpContext(
            string url = null, HttpVerbs? httpVerb = null)
        {
            var httpRequest = Substitute.For<HttpRequestBase>();

            if ((url != null) && !url.StartsWith("~/"))
            {
                httpRequest.Url.Returns(new Uri(url));
            }

            if (httpVerb != null)
            {
                httpRequest.HttpMethod
                           .Returns(httpVerb.ToString().ToUpperInvariant());
            }

            httpRequest.AppRelativeCurrentExecutionFilePath.Returns(url);
            httpRequest.ApplicationPath.Returns("/app/");

            var httpResponse = Substitute.For<HttpResponseBase>();
            httpResponse.ApplyAppPathModifier(Arg.Any<string>())
                        .Returns(x =>
                            ((string)x[0]).Contains(AppPathModifier) ?
                            (string)x[0] :
                            AppPathModifier + (string)x[0]);

            var httpContext = Substitute.For<HttpContextBase>();

            httpContext.Request.Returns(httpRequest);
            httpContext.Response.Returns(httpResponse);

            return httpContext;
        }
    }
}